﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.SearchUser;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Support.Constants;
using System.Collections.Generic;
using Microsoft.Office.Server.UserProfiles;
using MS.InformationManagement.Support;
using System.Web;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class SearchUser : BaseControl, ISearchUserView
    {
        #region fields

        private SearchUserPresenter _presenter;

        #endregion

        #region Properties

        public int UsuarioID { get; set; }
        public string UsuarioLoginName { get; set; }
        public string CedulaUsuario { get; set; }
        public string Departamento { get; set; }
        public List<UserProfile> listUsuariosDepartamento { get; set; }

        public int PageIndex
        {
            get
            {
                return pgrTemplates.PageIndex;
            }
            set
            {
                pgrTemplates.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return pgrTemplates.PageSize;
            }
            set
            {
                pgrTemplates.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return pgrTemplates.TotalRecords;
            }
            set
            {
                pgrTemplates.TotalRecords = value;
            }
        }

        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pgrTemplates.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
            //pgrTemplates.NextLinkText = ">>";
            //pgrTemplates.PreviousLinkText = "<<";
            pgrTemplates.NumberOfPagesToDisplay = 10;
            PageIndex = 0;
            PageSize = 10;
            pgrTemplates.BuildPager();
            txtCedula.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnCedula", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            if (!IsPostBack)
            {
                divBusqueda.Visible = false;
                divBtton.Visible = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            divGridResults.Visible = false;
            lblMensaje.Text = string.Empty;
            //ddlDeptos.isRequired = true;
            //ddlDeptos.ValidationGroup = "ValBtnDepartamentos";
            _presenter = new SearchUserPresenter(this);
        }

        protected void ddlBuscarPor_SelectedIndexChanged(object sender, EventArgs e)
        {
            divBusqueda.Visible = true;
            divBtton.Visible = true;
            gvUsuarios.DataSource = null;
            gvUsuarios.DataBind();
            CleanControl(false);
            switch (ddlBuscarPor.SelectedValue)
            {
                case "1":
                    lblCampoBusqueda.Text = "Cedula :";
                    btnSearch.ValidationGroup = "ValBtnCedula";
                    btnSearch.CausesValidation = true;
                    PeopleEditorUsuario.Visible = false;
                    deptSelector.Visible = false;
                    txtCedula.Visible = true;
                    btnSearch.Visible = true;
                    break;
                case "2":
                    lblCampoBusqueda.Text = "Usuario :";
                    btnSearch.CausesValidation = false;
                    PeopleEditorUsuario.Visible = true;
                    btnSearch.Visible = true;
                    txtCedula.Visible = false;
                    deptSelector.Visible = false;
                    break;
                case "3":
                    lblCampoBusqueda.Text = "Dependencia :";
                    btnSearch.ValidationGroup = "ValBtnDepartamentos";
                    btnSearch.CausesValidation = true;
                    PeopleEditorUsuario.Visible = false;
                    txtCedula.Visible = false;
                    btnSearch.Visible = true;
                    deptSelector.Visible = true;
                    break;
                default:
                    btnSearch.CausesValidation = false;
                    btnSearch.Visible = false;
                    txtCedula.Visible = false;
                    deptSelector.Visible = false;
                    divBusqueda.Visible = false;
                    divBtton.Visible = false;
                    PeopleEditorUsuario.Visible = false;
                    lblCampoBusqueda.Text = string.Empty;
                    break;
            }
        }

        protected void Action_Close(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        protected void Action_Search(object sender, EventArgs e)
        {
            PageIndex = 0;
            SearchByFilter();
            pgrTemplates.BuildPager();
        }

        private void SearchByFilter()
        {
            lblMensaje.Text = string.Empty;
            gvUsuarios.DataSource = null;
            gvUsuarios.DataBind();
            try
            {
                switch (ddlBuscarPor.SelectedValue)
                {
                    case "1":
                        CedulaUsuario = txtCedula.Text;
                        Departamento = null;
                        _presenter.HandleLoad();
                        break;
                    case "2":
                        Departamento = null;
                        PeopleEditorUsuario.Validate();
                        if (PeopleEditorUsuario.IsValid == true)
                        {
                            UsuarioID = SPContext.Current.Web.EnsureUser(PeopleEditorUsuario.CommaSeparatedAccounts).ID;
                            CleanControl(true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('El usuario no existe',' '); ", true);
                            CleanControl(false);
                        }
                        break;
                    case "3":
                        CedulaUsuario = string.Empty;
                        Departamento = deptSelector.SelectedDeparmentName;
                        _presenter.HandleLoad();
                        break;
                    default:
                        Departamento = null;
                        break;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvUsuarios_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvUsuarios.PageIndex = e.NewPageIndex;
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvUsuarios_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        protected void imgBtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            GridViewRow row = (GridViewRow)btn.NamingContainer;
            string userName = PeopleHelper.GetUserAccountName(gvUsuarios.DataKeys[row.RowIndex].Value.ToString());
            SPUser currentUser = SPContext.Current.Web.EnsureUser(userName);
            UsuarioID = currentUser.ID;
            gvUsuarios.DataSource = null;
            gvUsuarios.DataBind();
            CleanControl(true);

        }

        void pgrTemplates_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            SearchByFilter();
            pgrTemplates.BuildPager();
        }

        private void CleanControl(bool result)
        {
            ContentPlaceHolder mpContentPlaceHolder;
            mpContentPlaceHolder = (ContentPlaceHolder)Parent.Parent.FindControl("PlaceHolderMain");
            if (mpContentPlaceHolder != null)
            {
                GestionDeUsuariosUserControl GestionDeUsuariosUserCtrl = (GestionDeUsuariosUserControl)mpContentPlaceHolder.FindControl("UserInfoID");
                if (GestionDeUsuariosUserCtrl != null)
                {
                    if (result == true)
                        Cache["CurrentUserId"] = UsuarioID;
                    else
                        Cache["CurrentUserId"] = string.Empty;


                    GestionDeUsuariosUserCtrl.hideResult(result);
                }
            }
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {

            switch (ddlBuscarPor.SelectedValue)
            {
                case "1":
                    if (UsuarioID != 0)
                    {
                        CleanControl(true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('El usuario no existe',' '); ", true);
                        CleanControl(false);
                    }
                    break;
                case "3":
                    if (listUsuariosDepartamento.Count > 0)
                    {
                        gvUsuarios.DataSource = listUsuariosDepartamento;
                        gvUsuarios.DataBind();
                        divGridResults.Visible = true;
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('No se encontraron usuarios para el departamento seleccionado',' '); ", true);
                        CleanControl(false);
                    }
                    break;
                default:
                    Departamento = null;
                    break;
            }

        }

        #endregion


    }
}
